package com.woyou.fragment;

import java.util.ArrayList;
import java.util.List;

import com.jing.biandang.R;
import com.squareup.picasso.Picasso;
import com.woyou.activity.HomeActivity;
import com.woyou.adapter.MessageCommentAdapter;
import com.woyou.adapter.MessageSystemAdapter;
import com.woyou.adapter.SuperViewPagerAdapter;
import com.woyou.bean.CommentItem;
import com.woyou.bean.UserInfo;
import com.woyou.bean.rpc.QueryCommentListReq;
import com.woyou.bean.rpc.ReplyCommentReq;
import com.woyou.bean.rpc.Result;
import com.woyou.component.SuperUI;
import com.woyou.listener.ItemClickListener;
import com.woyou.listener.MessagePageChangeListener;
import com.woyou.model.rpc.ShopModel;
import com.woyou.utils.CharUtil;
import com.woyou.utils.FormatTools;
import com.woyou.utils.LoginUtils;
import com.woyou.utils.ThreadPoolManager;
import com.woyou.utils.TypeJudgeTools;

import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 消息和评论界面
 * 
 * @author zhou.ni
 *
 */
public class MessageFragment extends SuperFragment implements OnClickListener {
	private HomeActivity homeActivity;
	private View layout_message;
	private RelativeLayout layout_message_system_bar;
	private RelativeLayout layout_message_comment_bar;
	private int screenWidth;
	private ImageView layout_message_navi_iv;
	private ViewPager layout_message_vp;
	private SuperViewPagerAdapter superViewPagerAdapter;
	private View layout_message_system;
	private View layout_message_comment;

	// 信息列表
	private ListView layout_message_system_lv;
	private MessageSystemAdapter systemAdapter;

	// 评论列表
	private ListView layout_message_comment_lv;
	private MessageCommentAdapter commentAdapter;
	private List<CommentItem> comments = new ArrayList<CommentItem>();
	private int commentPage = 1;
	private int commentVisibleLast = 0;

	// 评论面板
	private LinearLayout layout_comment_panel;
	private ImageView layout_comment_icon;
	private TextView layout_comment_name;
	private TextView layout_comment_date;
	private TextView message_comment_info;
	private TextView replymessage;
	private EditText layout_comment_et;

	private Button layout_comment_send;
	private Button layout_comment_cancel;
	private String commentId = null;

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		if (!hidden) {
			comments.clear();
			commentPage = 1;
			layout_message_vp.setCurrentItem(1, false);
			loadCommentData(true);
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		layout_message = inflater.inflate(R.layout.layout_message, container, false);
		homeActivity=(HomeActivity)getActivity();
		return layout_message;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		// 计算位置
		DisplayMetrics dm = new DisplayMetrics();
		getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
		screenWidth = dm.widthPixels;
		layout_message_navi_iv = (ImageView) layout_message.findViewById(R.id.layout_message_navi_iv);
		LayoutParams layoutParams = layout_message_navi_iv.getLayoutParams();
		layoutParams.width = screenWidth / 2;
		layout_message_navi_iv.setLayoutParams(layoutParams);

		// 导航栏菜单
		layout_message_system_bar = (RelativeLayout) layout_message.findViewById(R.id.layout_message_system_bar);
		layout_message_comment_bar = (RelativeLayout) layout_message.findViewById(R.id.layout_message_comment_bar);
		// 初始化Viewpager
		layout_message_vp = (ViewPager) layout_message.findViewById(R.id.layout_message_vp);
		List<View> views = new ArrayList<View>();
		layout_message_system = View.inflate(homeActivity,R.layout.layout_message_system, null);
		layout_message_comment = View.inflate(homeActivity,R.layout.layout_message_comment, null);
		views.add(layout_message_system);
		views.add(layout_message_comment);
		superViewPagerAdapter = new SuperViewPagerAdapter(views);
		layout_message_vp.setAdapter(superViewPagerAdapter);
		layout_message_vp.setOnPageChangeListener(
				new MessagePageChangeListener(homeActivity, screenWidth, layout_message_navi_iv));
		// 设置导航监听器
		layout_message_system_bar.setOnClickListener(new ItemClickListener(0, layout_message_vp));
		layout_message_comment_bar.setOnClickListener(new ItemClickListener(1, layout_message_vp));
		// 初始化页面内容
		initSystem();
		initComment();
		layout_message_vp.setCurrentItem(1, false);
		loadCommentData(true);
	}

	/**
	 * 初始化系统消息
	 */
	public void initSystem() {

	}

	/**
	 * 初始化订单评论
	 */
	public void initComment() {
		layout_comment_panel = (LinearLayout) layout_message_comment.findViewById(R.id.layout_comment_panel);
		layout_comment_icon = (ImageView) layout_message_comment.findViewById(R.id.layout_comment_icon);
		layout_comment_name = (TextView) layout_message_comment.findViewById(R.id.layout_comment_name);
		message_comment_info = (TextView) layout_message_comment.findViewById(R.id.message_comment_info);
		layout_comment_date = (TextView) layout_message_comment.findViewById(R.id.layout_comment_date);
		replymessage = (TextView) layout_message_comment.findViewById(R.id.replymessage);

		layout_comment_et = (EditText) layout_message_comment.findViewById(R.id.layout_comment_et);
		layout_comment_send = (Button) layout_message_comment.findViewById(R.id.layout_comment_send);
		layout_comment_cancel = (Button) layout_message_comment.findViewById(R.id.layout_comment_cancel);
		layout_comment_send.setOnClickListener(this);
		layout_comment_cancel.setOnClickListener(this);
		final Button btn1 = (Button) layout_message_comment.findViewById(R.id.btnFirst);
		final Button btn2 = (Button) layout_message_comment.findViewById(R.id.btnSecond);
		final Button btn3 = (Button) layout_message_comment.findViewById(R.id.btnThirdly);
		final Button btn4 = (Button) layout_message_comment.findViewById(R.id.btnFourth);
		btn1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String content = layout_comment_et.getText().toString()
						+ btn1.getText().toString().replaceAll("\n", "");
				layout_comment_et.setText(content);
			}
		});
		btn2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String content = layout_comment_et.getText().toString()
						+ btn2.getText().toString().replaceAll("\n", "");
				layout_comment_et.setText(content);
			}
		});
		btn3.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String content = layout_comment_et.getText().toString()
						+ btn3.getText().toString().replaceAll("\n", "");
				layout_comment_et.setText(content);
			}
		});
		btn4.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String content = layout_comment_et.getText().toString()
						+ btn4.getText().toString().replaceAll("\n", "");
				layout_comment_et.setText(content);
			}
		});

		layout_message_comment_lv = (ListView) layout_message_comment.findViewById(R.id.layout_message_comment_lv);
		commentAdapter = new MessageCommentAdapter(homeActivity, this, comments);
		layout_message_comment_lv.setAdapter(commentAdapter);

		// 监听输入内容长度是否超出范围
		layout_comment_et.addTextChangedListener(new TextWatcher() {
			private String temp;
			private boolean flag = false;

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (flag) {
					return;
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				if (flag) {
					return;
				}
				temp = s.toString();
			}

			@Override
			public void afterTextChanged(Editable s) {
				if (flag) {
					flag = false;
					return;
				}
				if (CharUtil.GetStringNum(layout_comment_et.getText().toString()) <= 400) {
					replymessage.setText("您还可以输入"
							+ (Math.round(Math.floor(Integer.valueOf(
									(400 - CharUtil.GetStringNum(layout_comment_et.getText().toString())) / 2))))
							+ "个字");
				} else {
					Toast.makeText(homeActivity, "您输入的内容过长", Toast.LENGTH_SHORT).show();
					flag = true;
					layout_comment_et.setText(temp);
					layout_comment_et.setSelection(temp.length());

				}
			}
		});

		layout_comment_panel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				homeActivity.homeController.hideInputMethod();
			}
		});
		// 监听滚动事件
		layout_message_comment_lv.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE
						&& commentVisibleLast == (commentAdapter.getCount() - 1)) {
					if (commentPage != 0) {
						loadCommentData(false);
					}
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				commentVisibleLast = firstVisibleItem + visibleItemCount - 1;
			}
		});
	}

	/**
	 * 载入评论数据
	 * 
	 * @param isRefresh
	 *            isRefresh true:刷新列表，false 添加数据
	 */
	public void loadCommentData(final boolean isRefresh) {
		ThreadPoolManager.getInstance().executeTask(new Runnable() {
			@Override
			public void run() {
				try {
					homeActivity.showLoadingHint();

					if (isRefresh) {
						commentPage = 1;
					}
					QueryCommentListReq queryCommentListReq = new QueryCommentListReq();
					UserInfo userInfo = LoginUtils.getUserInfo(homeActivity);
					if (userInfo != null) {
						queryCommentListReq.setsId(userInfo.getsId());
						queryCommentListReq.setPwd(userInfo.getPwd());
					}
					queryCommentListReq.setPage(commentPage);
					final Result<List<CommentItem>> result = ShopModel.getInstance(homeActivity)
							.queryCommentList(queryCommentListReq);
					if (result != null && result.code == 1) {
						homeActivity.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								List<CommentItem> list = result.getData();
								if (list != null && list.size() > 0) {
									if (isRefresh) {
										commentPage = result.getPage();
										comments.clear();
										comments.addAll(list);
										commentAdapter.notifyDataSetInvalidated();
									} else {
										commentPage = result.getPage();
										comments.addAll(list);
										commentAdapter.notifyDataSetChanged();
									}
								}
							}
						});
					} else if (result != null && result.code == -3) {
						homeActivity.homeController.exitLogin();
					} else {
						homeActivity.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								SuperUI.openToast(homeActivity, "很抱歉,服务器又任性了");
							}
						});
					}
				} catch (Exception e) {
					homeActivity.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							SuperUI.openToast(homeActivity, "很抱歉,服务器又任性了");
						}
					});
				} finally {
					homeActivity.hideLoadingHint();
				}
			}
		});
	}

	/**
	 * 显示评论面板
	 */
	public void showCommentPanel(CommentItem comment) {
		if (comment != null) {
			commentId = comment.getcId();
			layout_comment_name.setText("" + comment.getuName());

			// 设置评论时间
			long cTime = comment.getcTime();
			if (cTime != 0) {
				String commentTime = FormatTools.convertTimeToFormat(homeActivity, cTime);
				layout_comment_date.setText(commentTime);
			} else {
				layout_comment_date.setText("");
			}

			// 加载用户头像
			if (!TypeJudgeTools.isNull(comment.getuPic())) {
				Picasso.with(homeActivity).load(comment.getuPic()).into(layout_comment_icon);
			} else {
				layout_comment_icon.setImageResource(R.raw.icon_analysis_customer);
			}

			if (!TextUtils.isEmpty(comment.getComments())) {
				message_comment_info.setText("" + comment.getComments());
			} else {
				message_comment_info.setText("");
			}

		}

		layout_message_comment_lv.setVisibility(View.GONE);
		layout_comment_panel.setVisibility(View.VISIBLE);
	}

	/**
	 * 隐藏评论面板
	 */
	public void hideCommentPanel() {
		layout_comment_et.setText("");
		layout_message_comment_lv.setVisibility(View.VISIBLE);
		layout_comment_panel.setVisibility(View.GONE);
		homeActivity.hideInputMethod();
	}

	/**
	 * 回复评论
	 */
	private void replyComment() {

		final String str = layout_comment_et.getText().toString();
		if (TypeJudgeTools.isEmpty(str)) {
			SuperUI.openToast(homeActivity, "回复的内容不能为空");
			return;
		}

		ThreadPoolManager.getInstance().executeTask(new Runnable() {
			@Override
			public void run() {
				try {
					homeActivity.showLoadingHint();

					ReplyCommentReq replyCommentReq = new ReplyCommentReq();
					UserInfo userInfo = LoginUtils.getUserInfo(homeActivity);
					if (userInfo != null) {
						replyCommentReq.setsId(userInfo.getsId());
						replyCommentReq.setPwd(userInfo.getPwd());
					}
					replyCommentReq.setContent(TypeJudgeTools.replaceBlank(str));
					replyCommentReq.setcId(commentId);
					Result result = ShopModel.getInstance(homeActivity).replyComment(replyCommentReq);
					if (result != null && result.getCode() == 1) {
						homeActivity.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								SuperUI.openToast(homeActivity, "回复成功");
								commentPage = 1;
								comments.clear();
								loadCommentData(true);
								hideCommentPanel();
							}
						});
					} else if (result != null && result.code == -3) {
						homeActivity.homeController.exitLogin();
					} else {
						homeActivity.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								SuperUI.openToast(homeActivity, "回复失败");
							}
						});
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					homeActivity.hideLoadingHint();
				}
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layout_message_system_bar:
			break;
		case R.id.layout_message_comment_bar:
			break;
		case R.id.layout_comment_send:
			replyComment();
			break;
		case R.id.layout_comment_cancel:
			hideCommentPanel();
			break;
		}
	}

}
